package com.example.administrator.text;


import android.os.Bundle;

import com.example.administrator.text.utils.LogUtil;
import com.example.administrator.text.utils.getEquipmentData;
import com.uzmap.pkg.openapi.ExternalActivity;
import com.uzmap.pkg.openapi.Html5EventListener;
import com.uzmap.pkg.openapi.WebViewProvider;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 启动  页
 */
public class MainActivity extends ExternalActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        EventBus.getDefault().register(this);
        getAddHtml5EventListener();
    }

    /**
     *监听APICloud的事件
     */
    private void getAddHtml5EventListener(){
        /**
         *  1：代表需要APICloud加载完需要传入的参数
         */
        addHtml5EventListener(new Html5EventListener("AppReceiveMessage") {
            @Override
            public void onReceive(WebViewProvider webViewProvider, Object o) {
                JSONObject jsonObject;
                try {
                    LogUtil.eE("","....apiloud发来的消息...."+o.toString());
                    jsonObject = new JSONObject(o.toString());
                    switch (jsonObject.getInt("type")){
                        case 1:
                            sendOutinitDataAPIIcoud();
                            break;
                        case 2:
                            moveTaskToBack(true);
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * 发送初始化数据给APlIcoud
     */
    private void sendOutinitDataAPIIcoud() throws JSONException {
        JSONObject extra = new JSONObject();
        extra.put("type","networkChange");
        extra.put("wifiName", getEquipmentData.newInstance(this).getWIFIName());
        extra.put("wifiIp",getEquipmentData.newInstance(this).getI_IP());
        extra.put("apMac",getEquipmentData.newInstance(this).getWiFiMac());
        extra.put("phoneMac",getEquipmentData.newInstance(this).getIMAC());
        sendEventToHtml5("appApicloudData",extra);
    }


    /*** 订阅事件FirstEvent*/
    @Subscribe
    public void onEventMainThread(String string) throws JSONException {
        if(string !=null){
            LogUtil.eE("","....onEventMainThread...."+string);
            if(string.equals("networkChange")){
                sendOutinitDataAPIIcoud();
            }else if(string.equals("weChatPay")){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type","weChatPay");
                sendEventToHtml5("appApicloudData",jsonObject);
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
